/**
 * \file ls_ble_mem.c
 *
 * \brief 
 */
 
#include "ls_ble_mem.h"
#include "ls_ble_heap.h"
#include "ls_ble_sdk_config.h"


#define LS_BLE_MEM_LOG_EN   0

#if LS_BLE_MEM_LOG_EN
#include "log.h"
#define LS_BLE_MEM_LOG      LOG
#else
#define LS_BLE_MEM_LOG(...)
#endif



void ls_ble_mem_init(void)
{
    prvLsHeapInit();
}


#if (LS_BLE_USE_PLATFORM_MEMORY_HEAP == 0)

/**
 *@brief      Allocate and clear a memory block with required size.   
 *@param[in]  size     Required memory size.   
 *        
 *@note     
 *           
 * */
void *ls_ble_malloc(uint16_t size)
{
    uint8_t *ptr = pvLsPortMalloc(size);
    if(ptr) {
        LS_BLE_MEM_LOG("malloc: %x, (%d)\n", ptr, size);
        memset(ptr, 0, size);   //allocate buffer need init
    }
    return ptr;
}


/**
 *@brief    
 *@param    
 *        
 *@note     
 *           
 * */
void *ls_ble_calloc_n(uint32_t n, uint32_t size)
{
    void *ptr = pvLsPortMalloc(n * size);
    if(ptr != NULL) {
        LS_BLE_MEM_LOG("calloc: %x, (%d)\n", ptr, (n*size));
        memset(ptr, 0, n * size);
    }
    else {
        LS_BLE_MEM_LOG("Err calloc fail\n");
    }
    return ptr;
}


/**
 *@brief    
 *@param    
 *        
 *@note     
 *           
 * */
void *ls_ble_realloc_n(void *ptr, size_t size)
{
    void *new_ptr = pvLsPortMalloc(size);
    if(new_ptr != NULL) {
        LS_BLE_MEM_LOG("realloc: %x, %x, (%d)\n", ptr, new_ptr, size);
        memcpy(new_ptr, ptr, size);
        vLsPortFree(ptr);
    }
    return new_ptr;
    //return pvLsPortRealloc(ptr, size);
}


/**
 *@brief    Free a memory block that had been allocated.
 *@param[in] ptr    The address of memory block being freed.
 *        
 *@note     
 *           
 * */
ls_ble_status_t ls_ble_free(void *ptr)
{
    if(ptr == NULL) {
        return LS_BLE_SUCCESS;
    }
    LS_BLE_MEM_LOG("free: %x\n", ptr);
    vLsPortFree(ptr);
    return LS_BLE_SUCCESS;
}


/**
 *@brief    
 *@param    
 *        
 *@note     
 *           
 * */
void ls_ble_free_n(void *ptr)
{
    vLsPortFree(ptr);
}

#else


/**
 *@brief      Allocate and clear a memory block with required size.   
 *@param[in]  size     Required memory size.   
 *        
 *@note     
 *           
 * */
void *ls_ble_malloc(uint16_t size)
{
    uint8_t *ptr = ls_ble_port_malloc(size);
    if(ptr) {
        memset(ptr, 0x0, size);//allocate buffer need init
    }
    return ptr;
}


/**
 *@brief    Free a memory block that had been allocated.
 *@param[in] ptr    The address of memory block being freed.
 *        
 *@note     
 *           
 * */
ls_ble_status_t ls_ble_free(void *ptr)
{
    if(ptr == NULL) {
        return TUYA_BLE_SUCCESS;
    }
    ls_ble_port_free(ptr);
    return LS_BLE_SUCCESS;
}


#endif



